package com.ncamc.pms.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ncamc.pms.api.common.enums.DispatchJobParamTypeEnum;
import com.ncamc.pms.core.common.constants.ExceptionCodeEnum;
import com.ncamc.pms.core.common.vo.DispatchJobParamReqVO;
import com.ncamc.pms.core.common.vo.DispatchJobRunReqVO;
import com.ncamc.pms.core.entity.DispatchJobInfo;
import com.ncamc.pms.core.exception.ApplicationException;
import com.ncamc.pms.core.mapper.DispatchJobInfoServiceMapper;
import com.ncamc.pms.core.service.DispatchJobInfoService;
import com.ncamc.pms.core.service.KettleTransService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DispatchJobInfoServiceImpl extends ServiceImpl<DispatchJobInfoServiceMapper, DispatchJobInfo> implements DispatchJobInfoService {

    @Autowired
    private DispatchJobInfoServiceMapper dispatchJobInfoServiceMapper;
    @Autowired
    private KettleTransService kettleTransService;

    @Override
    public void runJob(DispatchJobRunReqVO reqVO) {
        if (reqVO == null || StrUtil.isBlank(reqVO.getJobCode())) {
            return;
        }
        // 查询任务参数
        DispatchJobInfo dispatchJobInfo = lambdaQuery().eq(DispatchJobInfo::getJobCode, reqVO.getJobCode()).oneOpt().orElse(null);
        if (dispatchJobInfo == null || StrUtil.isBlank(dispatchJobInfo.getJobParams())) {
            return;
        }
        String jobParamStr = dispatchJobInfo.getJobParams();
        DispatchJobParamReqVO jobParam;
        try {
            jobParam = JSON.parseObject(jobParamStr, DispatchJobParamReqVO.class);
        } catch (Exception e) {
            throw new ApplicationException(ExceptionCodeEnum., e);
        }
        if (jobParam == null || CollUtil.isEmpty(jobParam.getTasks())) {
            return;
        }
        // 依次执行任务
        for (DispatchJobParamReqVO.Task task : jobParam.getTasks()) {
            // 调用调度
            if (DispatchJobParamTypeEnum.kettle.name().equals(task.getType())) {
                kettleTransService.runKettleProcessor(task.getKettleCode());
            } else if (DispatchJobParamTypeEnum.http.name().equals(task.getType())) {
                // 调用http
            } else if (DispatchJobParamTypeEnum.sql.name().equals(task.getType())) {
                // 执行sql
            }
        }
    }
}
